<template>
  <div class="smartlock-use-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>智能门锁使用</h2>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          @click="refreshData" 
          :loading="loading"
          icon="el-icon-refresh"
          size="medium"
        >
          刷新数据
        </el-button>
      </div>
    </div>


    <!-- 搜索和筛选栏 -->
    <el-form :inline="true" @submit.native.prevent class="search-form">
      <el-form-item>
        <el-input
          v-model="searchKeyword"
          @keyup.native.enter="handleSearch"
          @input="handleSearch"
          placeholder="搜索设备名称、学院、教室或IP地址"
          style="width: 280px; margin-right: 15px"
          clearable
        >
          <i slot="prefix" class="el-icon-search"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select 
          v-model="filters.status" 
          @change="handleFilter"
          placeholder="设备状态"
          style="width: 120px; margin-right: 15px"
          clearable
        >
          <el-option label="全部状态" value=""></el-option>
          <el-option label="已开锁" value="1"></el-option>
          <el-option label="已锁定" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select 
          v-model="filters.college" 
          @change="handleFilter"
          placeholder="学院筛选"
          style="width: 150px; margin-right: 15px"
          clearable
        >
          <el-option label="全部学院" value=""></el-option>
          <el-option 
            v-for="college in collegeList" 
            :key="college" 
            :label="college" 
            :value="college"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button 
          @click="resetFilters"
          icon="el-icon-refresh"
        >
          重置
        </el-button>
      </el-form-item>
      <!-- 批量操作区域 -->
      <el-form-item v-if="selectedLocks.length > 0">
        <span class="selected-count">已选择 {{ selectedLocks.length }} 个设备</span>
      </el-form-item>
      <el-form-item v-if="selectedLocks.length > 0">
        <el-button 
          type="success" 
          @click="batchUnlock"
          :loading="batchUnlocking"
          icon="el-icon-unlock"
          size="small"
        >
          批量开锁
        </el-button>
      </el-form-item>
      <el-form-item v-if="selectedLocks.length > 0">
        <el-button 
          type="warning" 
          @click="batchLock"
          :loading="batchLocking"
          icon="el-icon-lock"
          size="small"
        >
          批量关锁
        </el-button>
      </el-form-item>
      <el-form-item v-if="selectedLocks.length > 0">
        <el-button 
          @click="clearSelection"
          icon="el-icon-close"
          size="small"
        >
          清空选择
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 加载状态 -->
    <el-empty 
      v-if="loading" 
      description="正在加载设备数据..."
      style="padding: 4rem 2rem; background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);"
    >
      <i class="el-icon-loading" style="font-size: 36px;"></i>
    </el-empty>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <div class="error-icon">
        <i class="fas fa-exclamation-triangle"></i>
      </div>
      <h3>加载失败</h3>
      <p>{{ error }}</p>
      <el-button 
        type="primary" 
        @click="loadLocks"
        icon="el-icon-refresh"
      >
        重试
      </el-button>
    </div>

    <!-- 门锁设备表格 -->
    <el-table
      v-else-if="paginatedLocks.length > 0"
      :data="paginatedLocks"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="60" align="center">
      </el-table-column>
      
      <el-table-column label="选择" width="60" align="center">
        <template slot="header">
          <el-checkbox 
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          ></el-checkbox>
        </template>
        <template slot-scope="scope">
          <el-checkbox 
            :value="selectedLocks.includes(scope.row.lockId)"
            @input="toggleLockSelection(scope.row.lockId, $event)"
          ></el-checkbox>
        </template>
      </el-table-column>
      
      <el-table-column prop="name" label="设备名称" align="center" width="200">
      </el-table-column>
      
      <el-table-column prop="college" label="学院" align="center" width="120">
      </el-table-column>
      
      <el-table-column prop="classroom" label="教室" align="center" width="120">
      </el-table-column>
      
      <el-table-column prop="ipAddress" label="IP地址" align="center" width="120">
      </el-table-column>
      
      <el-table-column prop="status" label="设备状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.statusClass === 'unlocked' ? 'success' : 'warning'"
            size="small"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="remarks" label="通道号" align="center" show-overflow-tooltip>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button
            :type="scope.row.switchStatus === 1 ? 'warning' : 'primary'"
            @click="toggleLockStatus(scope.row)"
            :loading="scope.row.operating"
            :icon="scope.row.switchStatus === 1 ? 'el-icon-lock' : 'el-icon-unlock'"
            size="mini"
          >
            {{ scope.row.switchStatus === 1 ? '关锁' : '开锁' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div v-if="filteredLocks.length > 0" class="pagination-wrapper">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[16, 32, 48, 64]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredLocks.length"
        background
      >
      </el-pagination>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!loading && filteredLocks.length === 0" class="empty-state">
      <el-empty 
        :description="searchKeyword || filters.status || filters.college ? '没有找到符合条件的设备' : '暂无智能门锁设备'"
      >
        <el-button 
          v-if="searchKeyword || filters.status || filters.college"
          slot="bottom"
          @click="resetFilters"
          icon="el-icon-refresh"
        >
          清除筛选条件
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script>
// 接口路径常量定义
const SMARTLOCK_API = {
  LOCK_SELECT_ALL: '/api/smart/lock/selectAll',
  LOCK_UPDATE_STATUS: '/api/smart/lock/updateSwitchStatus',
  LOCK_COUNT_STATS: '/api/smart/lock/countNum'
};

export default {
  name: 'SmartLockUse',
  
  data() {
    return {
      // 数据状态
      locks: [],
      loading: false,
      error: null,
      
      // 搜索和筛选
      searchKeyword: '',
      filters: {
        status: '',
        college: ''
      },
      
      // 分页
      currentPage: 1,
      pageSize: 16,
      
      // 批量选择
      selectedLocks: [],
      batchUnlocking: false,
      batchLocking: false
    }
  },
  
  computed: {
    // 学院列表（用于筛选）
    collegeList() {
      const colleges = [...new Set(this.locks.map(lock => lock.college).filter(college => college && college !== '-'))];
      return colleges.sort();
    },
    
    // 搜索和筛选后的门锁列表
    filteredLocks() {
      let filtered = [...this.locks];
      
      // 关键词搜索
      if (this.searchKeyword && this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        filtered = filtered.filter(lock => {
          return (
            lock.name.toLowerCase().includes(keyword) ||
            (lock.college && lock.college.toLowerCase().includes(keyword)) ||
            (lock.classroom && lock.classroom.toLowerCase().includes(keyword)) ||
            (lock.ipAddress && lock.ipAddress.toLowerCase().includes(keyword)) ||
            (lock.snCode && lock.snCode.toLowerCase().includes(keyword))
          );
        });
      }
      
      // 状态筛选
      if (this.filters.status !== '' && this.filters.status !== null) {
        const statusValue = parseInt(this.filters.status);
        filtered = filtered.filter(lock => lock.switchStatus === statusValue);
      }
      
      // 学院筛选
      if (this.filters.college && this.filters.college.trim()) {
        filtered = filtered.filter(lock => lock.college === this.filters.college);
      }
      
      return filtered;
    },
    
    // 分页后的门锁列表
    paginatedLocks() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredLocks.slice(start, end);
    },
    
    // 全选相关计算属性
    checkAll: {
      get() {
        return this.filteredLocks.length > 0 && 
               this.selectedLocks.length === this.filteredLocks.length;
      },
      set(val) {
        // 这个setter会被handleCheckAllChange处理
      }
    },
    
    isIndeterminate() {
      const selectedCount = this.selectedLocks.length;
      return selectedCount > 0 && selectedCount < this.filteredLocks.length;
    },
    
    getSelectAllText() {
      if (this.checkAll) {
        return '取消全选';
      } else if (this.isIndeterminate) {
        return '全选';
      } else {
        return '全选';
      }
    }
  },
  
  mounted() {
    this.checkAuth();
    this.loadLocks();
  },
  
  methods: {
    // 检查认证状态
    checkAuth() {
      const Cookie = require('js-cookie');
      const token = Cookie.get('token');
      if (!token || token.trim() === '') {
        this.$message.error('请先登录');
        this.$router.push('/login');
        return false;
      }
      return true;
    },
    
    // 加载门锁数据
    loadLocks() {
      if (!this.checkAuth()) return;
      
      this.loading = true;
      this.error = null;
      
      this.$get(SMARTLOCK_API.LOCK_SELECT_ALL).then(res => {
        if (res && res.code === 200) {
          let locks = res.data || [];
          
          // 格式化门锁数据
          this.locks = locks.map(lock => {
            const formatted = this.formatLockInfo(lock);
            return {
              ...formatted,
              operating: false // 添加操作状态标识
            };
          });
          
          console.log('门锁数据加载完成:', this.locks);
          
          if (this.locks.length > 0) {
            this.$message.success('成功加载 ' + this.locks.length + ' 个智能锁设备');
          }
        } else if (res && res.msg) {
          this.error = '获取智能锁设备信息失败：' + res.msg;
          this.$message.error(this.error);
        } else {
          this.error = '获取智能锁设备信息失败：网络错误或后端服务未启动';
          this.$message.error(this.error);
        }
      }).catch(err => {
        console.error('API请求失败:', err);
        this.error = '获取智能锁设备信息失败：网络连接异常';
        this.$message.error(this.error);
        
        // 处理401未授权错误
        if (err.message && err.message.includes('401')) {
          const Cookie = require('js-cookie');
          Cookie.remove('token');
          this.$router.push('/login');
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 格式化锁信息
    formatLockInfo(lock) {
      return {
        lockId: lock.lockId || '',
        college: lock.college || '-',
        classroom: lock.classroom || '-',
        ipAddress: lock.ipAddress || '-',
        portNumber: lock.portNumber || '-',
        snCode: lock.snCode || '-',
        switchStatus: lock.switchStatus !== undefined ? lock.switchStatus : 0,
        remarks: lock.remarks || '-',
        onlineStatus: lock.onlineStatus !== undefined ? lock.onlineStatus : 0,
        // 计算显示属性
        name: lock.college && lock.classroom ? `${lock.college}-${lock.classroom}` : `设备${lock.lockId || ''}`,
        status: lock.switchStatus === 1 ? '已开锁' : '已关锁',
        statusClass: lock.switchStatus === 1 ? 'unlocked' : 'locked',
        statusIcon: lock.switchStatus === 1 ? 'fas fa-unlock' : 'fas fa-lock'
      };
    },
    
    // 处理搜索
    handleSearch() {
      // 搜索时重置到第一页
      this.currentPage = 1;
      console.log('搜索关键词:', this.searchKeyword);
    },
    
    // 处理筛选
    handleFilter() {
      // 筛选时重置到第一页
      this.currentPage = 1;
      console.log('筛选条件:', this.filters);
    },
    
    // 重置筛选条件
    resetFilters() {
      this.searchKeyword = '';
      this.filters.status = '';
      this.filters.college = '';
      this.currentPage = 1;
      this.$message.info('已重置搜索和筛选条件');
    },
    
    // 分页处理
    handleCurrentChange(page) {
      this.currentPage = page;
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1; // 改变页面大小时重置到第一页
    },
    
    // 开锁/关锁切换
    toggleLockStatus(lock) {
      if (!this.checkAuth()) return;
      if (lock.operating) return;
      
      const targetStatus = lock.switchStatus === 1 ? 0 : 1; // 切换状态
      const actionText = targetStatus === 1 ? '开锁' : '关锁';
      
      // 弹出确认对话框
      this.$confirm(`确定要${actionText} "${lock.name}" 吗？`, `${actionText}确认`, {
        confirmButtonText: `确定${actionText}`,
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        // 用户确认后执行操作
        this.executeLockOperation(lock, targetStatus, actionText);
      }).catch(() => {
        // 用户取消
        this.$message.info(`已取消${actionText}操作`);
      });
    },
    
    // 执行开锁/关锁操作
    executeLockOperation(lock, targetStatus, actionText) {
      lock.operating = true;
      
      this.$post(SMARTLOCK_API.LOCK_UPDATE_STATUS, {
        lockId: lock.lockId,
        switchStatus: targetStatus
      })
      .then(res => {
        if (res && res.code === 200) {
          this.$message.success(`${actionText}成功！`);
          
          // 更新本地状态
          lock.switchStatus = targetStatus;
          lock.status = targetStatus === 1 ? '已开锁' : '已关锁';
          lock.statusClass = targetStatus === 1 ? 'unlocked' : 'locked';
          lock.statusIcon = targetStatus === 1 ? 'fas fa-unlock' : 'fas fa-lock';
        } else {
          this.$message.error(res.msg || `${actionText}失败`);
        }
      })
      .catch(error => {
        console.error(`${actionText}失败:`, error);
        this.$message.error(`${actionText}失败: ` + error.message);
        
        // 处理401未授权错误
        if (error.message.includes('401')) {
          const Cookie = require('js-cookie');
          Cookie.remove('token');
          this.$router.push('/login');
        }
      })
      .finally(() => {
        lock.operating = false;
      });
    },
    
    // 旧的开锁方法（保留兼容性）
    unlockDevice(lock) {
      this.toggleLockStatus(lock);
    },
    
    // 刷新数据
    refreshData() {
      this.loadLocks();
    },
    
    // 批量选择相关方法
    toggleLockSelection(lockId, checked) {
      if (checked) {
        if (!this.selectedLocks.includes(lockId)) {
          this.selectedLocks.push(lockId);
        }
      } else {
        const index = this.selectedLocks.indexOf(lockId);
        if (index > -1) {
          this.selectedLocks.splice(index, 1);
        }
      }
    },
    
    clearSelection() {
      this.selectedLocks = [];
      this.$message.info('已清空选择');
    },
    
    // 全选/取消全选处理
    handleCheckAllChange(val) {
      if (val) {
        // 全选：选择当前筛选结果中的所有设备
        this.selectedLocks = this.filteredLocks.map(lock => lock.lockId);
        this.$message.success(`已选择 ${this.selectedLocks.length} 个设备`);
      } else {
        // 取消全选
        this.selectedLocks = [];
        this.$message.info('已取消全选');
      }
    },
    
    // 批量开锁
    batchUnlock() {
      this.executeBatchOperation(1, '开锁');
    },
    
    // 批量关锁
    batchLock() {
      this.executeBatchOperation(0, '关锁');
    },
    
    // 通用批量操作方法
    executeBatchOperation(targetStatus, actionText) {
      if (!this.checkAuth()) return;
      if (this.selectedLocks.length === 0) {
        this.$message.warning(`请先选择要${actionText}的设备`);
        return;
      }
      
      // 过滤出已选择的锁设备
      const selectedLockObjects = this.locks.filter(lock => 
        this.selectedLocks.includes(lock.lockId)
      );
      
      // 检查是否有设备已经是目标状态
      const alreadyInTargetStatus = selectedLockObjects.filter(lock => lock.switchStatus === targetStatus);
      if (alreadyInTargetStatus.length > 0) {
        const statusText = targetStatus === 1 ? '开锁' : '关锁';
        this.$message.warning(`有 ${alreadyInTargetStatus.length} 个设备已经是${statusText}状态，将跳过这些设备`);
      }
      
      // 过滤出需要操作的设备
      const locksToOperate = selectedLockObjects.filter(lock => lock.switchStatus !== targetStatus);
      
      if (locksToOperate.length === 0) {
        const statusText = targetStatus === 1 ? '开锁' : '关锁';
        this.$message.info(`所选设备都已经是${statusText}状态`);
        return;
      }
      
      // 弹出确认对话框
      this.$confirm(
        `确定要批量${actionText} ${locksToOperate.length} 个门锁吗？`, 
        `批量${actionText}确认`, 
        {
          confirmButtonText: `确定${actionText}`,
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      ).then(() => {
        this.executeBatchOperationAction(locksToOperate, targetStatus, actionText);
      }).catch(() => {
        this.$message.info(`已取消批量${actionText}操作`);
      });
    },
    
    // 执行批量操作
    executeBatchOperationAction(locks, targetStatus, actionText) {
      // 设置对应的loading状态
      if (targetStatus === 1) {
        this.batchUnlocking = true;
      } else {
        this.batchLocking = true;
      }
      
      let successCount = 0;
      let failCount = 0;
      let completedCount = 0;
      const totalCount = locks.length;
      
      this.$message.info(`开始批量${actionText}，共 ${totalCount} 个设备...`);
      
      // 并发执行所有操作
      locks.forEach(lock => {
        // 设置单个锁的操作状态
        lock.operating = true;
        
        this.$post(SMARTLOCK_API.LOCK_UPDATE_STATUS, {
          lockId: lock.lockId,
          switchStatus: targetStatus
        })
        .then(res => {
          if (res && res.code === 200) {
            successCount++;
            // 更新本地状态
            lock.switchStatus = targetStatus;
            lock.status = targetStatus === 1 ? '已开锁' : '已关锁';
            lock.statusClass = targetStatus === 1 ? 'unlocked' : 'locked';
            lock.statusIcon = targetStatus === 1 ? 'fas fa-unlock' : 'fas fa-lock';
          } else {
            failCount++;
            console.error(`${actionText}失败:`, lock.name, res.msg);
          }
        })
        .catch(error => {
          failCount++;
          console.error(`${actionText}失败:`, lock.name, error);
        })
        .finally(() => {
          lock.operating = false;
          completedCount++;
          
          // 所有操作完成后显示结果
          if (completedCount === totalCount) {
            // 重置loading状态
            this.batchUnlocking = false;
            this.batchLocking = false;
            
            if (successCount > 0) {
              this.$message.success(`批量${actionText}完成！成功 ${successCount} 个，失败 ${failCount} 个`);
            } else {
              this.$message.error(`批量${actionText}失败，请检查网络连接或设备状态`);
            }
            
            // 清空选择
            this.clearSelection();
          }
        });
      });
    }
  }
}
</script>

<style scoped>
.smartlock-use-container {
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  position: relative;
  /* 确保滚动平滑 */
  scroll-behavior: smooth;
  /* 防止内容溢出到父容器 */
  contain: layout style paint;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-left h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.header-right {
  display: flex;
  align-items: center;
}


.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.selected-count {
  color: #92400e;
  font-weight: 600;
  font-size: 14px;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table .cell {
  padding: 0 8px;
}

.el-table th {
  background-color: #fafafa;
}

.el-table--border td, .el-table--border th {
  border-right: 1px solid #ebeef5;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
}

/* 表单项间距 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 按钮组样式 */
.el-form-item:last-child {
  margin-right: 0;
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 8px;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.error-icon {
  font-size: 3rem;
  color: #f56c6c;
  margin-bottom: 1rem;
}

.error-state h3 {
  color: #333;
  margin-bottom: 0.5rem;
}

.error-state p {
  color: #666;
  margin-bottom: 2rem;
}

.empty-state {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 2rem;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 15px 0;
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .el-table {
    font-size: 13px;
  }
  
  .el-table .cell {
    padding: 0 6px;
  }
}

@media screen and (max-width: 768px) {
  .smartlock-use-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
    text-align: center;
  }
  
  .header-left h2 {
    border-bottom: none;
    padding-bottom: 0;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-form {
    padding: 15px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
    margin-right: 0;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .pagination-wrapper {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
}

/* 自定义滚动条样式 */
.smartlock-use-container::-webkit-scrollbar {
  width: 8px;
}

.smartlock-use-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
  margin: 4px;
}

.smartlock-use-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.smartlock-use-container::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.smartlock-use-container::-webkit-scrollbar-corner {
  background: transparent;
}
</style>
